package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpActivity extends AppCompatActivity {
    private TextView tvResponse;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_okhttp);
        initView();
    }

    private void initView() {
        tvResponse = findViewById(R.id.tv_OkHttp);
    }

    //使用OKHttp访问网络
    public void sendRequest(View view){
        sendRequestWithOkHttp("https://wwww.csdn.net", new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                showResponse("访问网络失败");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                //当访问网络成功，并得到返回的数据时
                showResponse(response.body().string());
            }
        });
    }

    private void sendRequestWithOkHttp(final String address, Callback callback){

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("https://www.csdn.net").build();
        client.newCall(request).enqueue(callback);
    }

    private void showResponse(final String response){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvResponse.setText(response);
            }
        });
    }
}